import Vue from 'vue'
import VueRouter from 'vue-router'
// import Login from '../views/login/index.vue'
// 把组件的引入改成函数的写法 ----打包之后，自动会有路由懒加载的效果
const Login = () => import('../views/login/index.vue')
// import Home from '../views/home/index.vue'
const Home = () => import('../views/home/index.vue')
// import Layout from '../views/layout/index.vue'
const Layout = () => import('../views/layout/index.vue')
import { getUser } from '../utils/storage'
// import Articles from '../views/articles/index.vue'
const Articles = () => import('../views/articles/index.vue')
// import Image from '../views/image/index.vue'
const Image = () => import('../views/image/index.vue')
// import AddArticle from '../views/articles/add.vue'
const AddArticle = () => import('../views/articles/add.vue')
// import EditArticle from '../views/articles/edit.vue'
const EditArticle = () => import('../views/articles/edit.vue')
// import NotFound from '../views/page404/index.vue'
const NotFound = () => import('../views/page404/index.vue')
// import Comment from '../views/comment/index.vue'
const Comment = () => import('../views/comment/index.vue')
// import Fans from '@/views/fans'
const Fans = () => import('@/views/fans')
// import Settings from '../views/settings/index.vue'
const Settings = () => import('../views/settings/index.vue')

Vue.use(VueRouter)
// 配置路由
const routes = [
  { path: '/login', name: 'login', component: Login },
  {
    path: '/',
    name: 'login',
    component: Layout,
    children: [
      // 主页
      { path: '', component: Home },
      // 文章管理
      { path: '/articles', component: Articles },
      // 发布文章
      { path: '/addarticle', component: AddArticle },
      // 编辑文章
      { path: '/editarticle/:id', component: EditArticle },
      // 素材管理
      { path: '/image', component: Image },
      // 评论管理
      { path: '/comment', component: Comment },
      // 粉丝管理
      { path: '/fans', component: Fans },
      // 个人设置
      { path: '/settings', component: Settings }
    ]
  },
  { path: '*', component: NotFound }
]

const router = new VueRouter({
  routes
})
// 路由导航守卫
// 所有页面跳转都会先进入到这个函数中
// to：要跳入的路由信息（去哪里），from要跳出的路由信息（从哪里来），next放行的方法
// next():允许进入到to的路由，正常跳转。next(路由地址)，不去to，去指定的路由地址
router.beforeEach((to, from, next) => {
  // console.log('路由导航守卫', to, from, next)
  // 检查是否有登录信息有就放行，无就去登录/看localStorage是否有信息
  if (to.path === '/') {
    const userInfo = getUser()
    if (userInfo && userInfo.token) {
      next()
    } else {
      console.log('路由导航守卫：要登录才能访问呦！')
      next('/login')
    }
  } else {
    // 如果不是去主页直接放行
    next()
  }
})
export default router
